import { create } from 'zustand';
import { defaultCheckedColumns } from './constant';
import { getFieldConfig } from '../OrderList/services';

// 创建状态管理器
export const useFilterFieldsConfig = create((set) => ({
  checkingMap: defaultCheckedColumns.reduce((pre, cur) => ({ ...pre, [cur.key]: true }), {}),
  isInitLoading: true,
  // 更新状态的方法
  updateCheckingMap: (newVal) => {
    set((state) => {
      return {
        ...state,
        ...newVal,
      }
    });
  },
  async initFieldConfig () {
    let checkingMap = {};
    try {
      const { success, data = {} } = await getFieldConfig({ code: 'ColsSettingOrderFilter' });
      if(success && data.param) {
        const obj = JSON.parse(data.param);
        defaultCheckedColumns.map(item=>{
          const field = item.key;
          checkingMap[field] = obj[field] == undefined ? true : obj[field];
        })
      }
    } catch (error) {
      console.error(error, 'error')
    }
    
    set((state) => {
      return {
        ...state,
        checkingMap: Object.keys(checkingMap)?.length ? checkingMap : state.checkingMap,
        isInitLoading: false,
      }
    })
  }
}));



